package io.github.heollhai.common.entity.vo.permissionTree;

import io.github.heollhai.common.entity.bo.PermissionBo;
import io.github.heollhai.common.utils.tree.AbstractTreeNode;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lmf
 * @Create: 2024/8/6 14:43
 * Description:
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class RouteVo extends AbstractTreeNode<RouteVo, Integer, Integer> {
    private Integer id;
    private Integer pid;
    /**
     * 路由菜单访问路径
     */
    private String path;
    /**
     * 路由 name
     */
    private String name;

    /**
     * 路由 name (对应页面组件 name, 可用作 KeepAlive 缓存标识 && 按钮权限筛选)
     */
    private String pathName;
    /**
     * 视图文件路径
     */
    private String component;
    /**
     * 路由重定向地址
     */
    private String redirect;
    /**
     * 路由元信息
     */
    private RouteMetaVo meta;
    /**
     * 操作类型
     */
    private String actionType;

    /**
     * 多个以逗号分割存储 (暂时最多一个)
     */
    private String metaRole;

    /**
     * 构建路由列表
     */
    public List<RouteVo> buildRouteList(List<PermissionBo> webPermissionList) {
        List<RouteVo> routeVos = new ArrayList<>();
        for (PermissionBo permissionBo : webPermissionList) {
            RouteVo routeVo = new RouteVo();

            // 构建web路由结构
            BeanUtils.copyProperties(permissionBo, routeVo);
            routeVo.setComponent(permissionBo.getComponentPath());

            RouteMetaVo routeMetaVo = buildRouteMetaVo(permissionBo);
            routeVo.setMeta(routeMetaVo);

            routeVos.add(routeVo);
        }

        return routeVos;
    }

    /**
     * 构建路由元信息
     */
    private RouteMetaVo buildRouteMetaVo(PermissionBo permissionBo) {
        RouteMetaVo routeMetaVo = new RouteMetaVo();
        routeMetaVo.setTitle(permissionBo.getMetaTitle());
        routeMetaVo.setIcon(permissionBo.getMetaIcon());
        routeMetaVo.setIsLink(permissionBo.getMetaIsLink());
        routeMetaVo.setFlag(permissionBo.getMetaFlag());
        routeMetaVo.setActiveMenu(permissionBo.getMetaActiveMenu());

        routeMetaVo.setIsHide(convertToBoolean(permissionBo.getMetaIsHide()));
        routeMetaVo.setIsAffix(convertToBoolean(permissionBo.getMetaIsAffix()));
        routeMetaVo.setIsKeepAlive(convertToBoolean(permissionBo.getMetaIsKeepAlive()));
        routeMetaVo.setIsFull(convertToBoolean(permissionBo.getMetaIsFull()));
        return routeMetaVo;
    }

    /**
     * 数字转 boolean类型
     */
    private boolean convertToBoolean(Integer value) {
        return value != null && value == 1;
    }

}
